package cn.xiaopengstack.domain.activity.service.quota.rule.chain;

import cn.xiaopengstack.domain.activity.model.entity.ActionRuleMatterEntity;
import cn.xiaopengstack.domain.activity.model.entity.RaffleActivityEntity;
import cn.xiaopengstack.domain.activity.model.entity.RaffleActivitySkuEntity;
import cn.xiaopengstack.domain.activity.model.valobj.ActivitySkuStockKeyVO;
import cn.xiaopengstack.domain.activity.repository.IRaffleActivityRepository;
import cn.xiaopengstack.domain.activity.service.quota.rule.factory.DefaultActivityActionChainFactory;
import cn.xiaopengstack.types.enums.ResponseCode;
import cn.xiaopengstack.types.exception.AppException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @author jiangyangang
 */
@Component
@Slf4j
public class DecrStockChain extends AbstractActionChain{

    @Resource
    private IRaffleActivityRepository raffleActivityRepository;

    @Override
    public boolean doChain(ActionRuleMatterEntity ruleMatter) {
        RaffleActivitySkuEntity activitySku = ruleMatter.getActivitySku();
        RaffleActivityEntity activity = ruleMatter.getActivity();
        // 扣减库存
        ActivitySkuStockKeyVO skuStockKeyVO = ActivitySkuStockKeyVO.builder()
                .sku(activitySku.getSku())
                .activityId(activitySku.getActivityId())
                .endTime(activity.getEndDateTime().toInstant().toEpochMilli())
                .decrNumber(1)
                .build();

        boolean decrStockResult = raffleActivityRepository.subtractionActivitySkuStock(skuStockKeyVO);

        if (decrStockResult) {
            log.info("库存扣减责任链，库存扣减成功，放入延时队列准备消费; {}", activitySku.getActivityId());
            // 放入延迟队列
            raffleActivityRepository.produceActivitySkuStockDecrQueue(skuStockKeyVO);
        } else {
            log.error("库存扣减责任链，库存不足; {}", activitySku.getActivityId());
            throw new AppException(ResponseCode.ACTIVITY_STOCK_SELL_OUT.getCode(), ResponseCode.ACTIVITY_STOCK_SELL_OUT.getInfo());
        }

        return next().doChain(ruleMatter);
    }

    @Override
    public DefaultActivityActionChainFactory.ActionEnum action() {
        return DefaultActivityActionChainFactory.ActionEnum.DECR_STOCK;
    }

    @Override
    public int getOrder() {
        return action().getOrder();
    }
}
